import React from 'react';
import PageTile from 'component/page-title/index.jsx';
import './index.scss';
import RichEditor from 'tool/rich-editor/index.jsx';
import FileUploader from 'tool/file-upload/index.jsx';
import CategorySearch from  'page/product/productList/CategorySearch.jsx';
import Product from  'service/product-service.jsx';
import Tool from  'tool/tool.jsx';
const _product = new Product();
const _req = new Tool();


//商品编辑组件
class SeveProduct extends React.Component{
  constructor(props){
    super(props);
    this.state={
      id: (this.props.location.state || {} ).pid || '',//添加商品过来没有state字段，会保存undefined
      categoryId: 0,
      parentCategoryId: 0,
      name: '',
      subtitle: '',
      subImages: [],
      detail: '',
      price: '',
      stock: '',
      status: 1 //添加商品时，给商品的默认状态为1，及在售
    };
    this.getImageString = this.getImageString.bind(this);
    this.loadProductDtail = this.loadProductDtail.bind(this);
  }
  //框架进行组件渲染前调用该方法，用于判断此次请求是否带id
  componentDidMount(){
     this.loadProductDtail();
  }
  loadProductDtail(){
    //id存在，表明是商品编辑请求,需要进行表单回填
   if(this.state.id){
     //去请求商品详情接口
     _product.getProductDetail(this.state.id).then(res=>{
       //请求成功，res中的subImages字段为字符串，将其装换成数组后，再将res存放当state中
        let images = res.subImages.split(',');
        res.subImages=images.map((imgUri)=>{
          return{
            uri: imgUri,
            url: `${res.imageHost}${imgUri}`
          }
        })
        //只有首次进去编辑，调用商品详情接口，才使用defaultDetail
        res.defaultDetail = res.detail;
        this.setState(res);
     },errMsg=>{
      _req.errorTips(errMsg);
     });
   }
  }
  //普通字段改变，例如：名称，描述，价格，库存
  onNormalValueChange(e){
   let inputName = e.target.name,
       inputValue = e.target.value;
    this.setState({
      [inputName] : inputValue
    })
  }
//选择了品类
onCategoryChange(categoryId,fatherCategoryId){
 this.setState({
  categoryId: categoryId,
  parentCategoryId: fatherCategoryId
 })
}
//图片上传成功，将res保存到数组中便于后面的显示和信息提交
onUploadSuccess(res){
  let {subImages} =this.state;
  subImages.push(res);
 this.setState({
    subImages 
 })
}
//上传图片失败
onUploadError(error){
  _req.errorTips(error || "上传图片失败！");
}
//删除图片
onImageDelete(e){
 let index = parseInt(e.target.getAttribute('index')),
     {subImages}  = this.state;
     subImages.splice(index,1);
     this.setState({
       subImages
     });
}
//富文本内容改变时，将内容保存到state中
onRichEidtorChange(value){
 this.setState({
   detail:value
 });
}
//将图片数组转成字符串
getImageString(){
  let images= this.state.subImages.map((image)=>(image.uri)).join(',');
  return images
}
//表单提交
onAllSubmit(){
  let product ={
    categoryId : parseInt(this.state.categoryId),
    name : this.state.name,
    subtitle : this.state.subtitle,
    subImages : this.getImageString(),
    detail : this.state.detail,
    price : parseFloat(this.state.price),
    stock : parseInt(this.state.stock),
    status : this.state.status
  }
  //如果是商品编辑，表单提交时还要带上商品id
  if(this.state.id){
    product.id = this.state.id;
  }
 //表单验证
 let productCheck = _product.onCheckProduct(product);
 //表单验证成功
 if(productCheck.status){
   _product.onSaveProduct(product).then(res=>{
     //成功后给出提示，并跳转回商品列表页
     _req.successTips(res);
     this.props.history.push('/product/index');
   },errMsg=>{
     _req.errorTips(errMsg);
   })
 }
 //表单验证失败
 else{
   _req.errorTips(productCheck.msg);
 }
}

 render(){
      return(
        <div id="page-wrapper">
          <PageTile title={this.state.id ? "编辑商品" : "添加商品"}/>
          <div className="row"> 
              <div className="col-md-12">
                <div className="form-horizontal">
                    <div className="form-group">
                      <label className="col-md-2 control-label">商品名称</label>
                      <div className="col-md-5">
                        <input type="text" 
                               className="form-control" 
                               value={this.state.name}
                               name="name"
                               onChange={e=>this.onNormalValueChange(e)}
                               placeholder="请输入商品名称"/>
                      </div>
                    </div>
                    <div className="form-group">
                      <label  className="col-md-2 control-label">商品描述</label>
                      <div className="col-md-5">
                        <input type="text" 
                               className="form-control" 
                               value={this.state.subtitle}
                               name="subtitle"
                               onChange={e=>this.onNormalValueChange(e)}
                               placeholder="请输入商品描述"/>
                      </div>
                    </div>
                    <CategorySearch  categoryId={this.state.categoryId}  parentCategoryId={this.state.parentCategoryId}
                                     onFatherCategoryChange={(categoryId,fatherCategoryId)=>{this.onCategoryChange(categoryId,fatherCategoryId)}} />
                    <div className="form-group">
                      <label  className="col-md-2 control-label">商品价格</label>
                      <div className="col-md-3">
                        <div className="input-group">
                          <input type="number" 
                                 className="form-control" 
                                 value={this.state.price}
                                 name="price"
                                 onChange={e=>this.onNormalValueChange(e)}
                                 placeholder="价格"/>
                          <span className="input-group-addon">元</span>
                        </div>
                      </div>
                    </div>
                    <div className="form-group">
                      <label  className="col-md-2 control-label">商品库存</label>
                      <div className="col-md-3">
                        <div className="input-group">
                          <input type="number" 
                                 className="form-control" 
                                 value={this.state.stock}
                                 name="stock"
                                 onChange={e=>this.onNormalValueChange(e)}
                                 placeholder="库存"/>
                          <span className="input-group-addon">件</span>
                        </div>
                      </div>
                    </div>
                    <div className="form-group img-wrapper">
                      <label  className="col-md-2 control-label">商品图片</label>
                      <div>
                        <div className="col-md-10 imgs-box">
                          {this.state.subImages.length !==0 
                            ? this.state.subImages.map((image,index)=>(
                              <div key={index} className="images">
                                <img src={image.url}/>
                                <i className="fa fa-close" index={index} onClick={e=>this.onImageDelete(e)}></i>
                              </div>
                              ))
                            : <div>请上传图片</div>
                          }
                        </div>
                        <div className="col-md-10">
                          <FileUploader onSuccess={(res)=>this.onUploadSuccess(res)} onError={(error)=>this.onUploadError(error)} />
                        </div>
                      </div>
                    </div>
                    <div className="form-group">
                      <label  className="col-md-2 control-label">商品详情</label>
                      <div className="col-md-10 control-label">
                        <RichEditor 
                           defaultDetail={this.state.defaultDetail}
                           onValueChange={(value)=>{this.onRichEidtorChange(value)}}/>
                      </div>
                      </div>
                    <div className="form-group">
                      <div className="col-md-offset-2 col-md-10">
                        <button type="submit" className="btn btn-primary" onClick={e=>{this.onAllSubmit()}}>提交</button>
                      </div>
                    </div>
                </div>
              </div>
           </div>
        </div>
      )
    }
  }
export default SeveProduct;

